{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# How to predict catastrophic events ?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Introduction "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "At the end of that short but preciser tutorial, you'll understand what is a GEV (Generalized extreme value distribution) and how to fit it on your data in python. \n",
    "\n",
    "What we need to think about before speaking of extreme values statistics, is that in general statistics focus on average values and observable phenomenoms, for which we **do have datas**. Extreme values statistics is different from \"average\" statistics in this regard, indeed as we will see, we here try to model something for which **we have no data!** You will see soon what we mean by that. Before getting there I want to show you why extreme values modelling is an actual problem, of high interest for insurance companies and public services. Let's start with two examples."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### <center> Montpellier, France, 2014\n",
    "**3 hours of rain = 50% of total annual average.** *Montpellier is not known to be a city with a high annual rain level, located in the dry location of Provence, therefore if we look at the average value we have a very common one. But it is not excluded that sometimes, rarely, very high values appear, as we can see:*\n",
    "\n",
    "<img align=\"center\" src=\"https://s1.lemde.fr/image2x/2014/10/07/0x0/4501632_5_f1d0_a-picture-taken-on-october-7-2014-shows-a_98f1f199a7769f5add31267568c48d85.jpg\" style=\"width: 700px;\"/>\n",
    "<br>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### <center> Saltina river in Brigue, Switzerland, 1993\n",
    "**Unprecedented measured flows and precipitations in the twentieth century**.\n",
    "*Same problem here, this rivers has reasonable flows in average, but sometimes the flow can be exceptional.*\n",
    "<img align=\"center\" src=\"http://www.planat.ch/uploads/pics/p0032_01.jpg\" style=\"width: 600px;\"/>\n",
    "<br>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### <center> Number of natural catastrophes since 1980 is growing \n",
    "**Those \"extreme\" events tends to become more and numerous those days, and make extreme value analysis \"popular\".**\n",
    "<img align=\"center\" src=\"https://cdn.static-economist.com/sites/default/files/images/2017/08/blogs/graphic-detail/20170902_woc210.png\" style=\"width: 600px;\"/>\n",
    "<br>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### <center> Some could wonder what statistical model shall we use to predict a Nadal loss at Roland Garros \n",
    "\n",
    "<img align=\"center\" src=\"https://www.freebetreview.com.au/Images/blog/rafael-nadal-french-open-record-infographic.png\" style=\"width: 600px;\"/>\n",
    "<br>\n",
    "<center> (Almost) just kidding"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Question: What if we would like to quantify the probability of such events ?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As we said the particularity of the extreme value analysis is not to model an average phenomenom but an extreme phenomenom."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In order to understand what we mean by that, let's work with the Nidd river dataset here : https://www.stat.auckland.ac.nz/~wild/data/Rdatasets/csv/evir/nidd.thresh.csv, it contains $n=154$ trimestrial measures of the river's flows (in $m³/s$), over a period of 38.5 years (source: Natural Environment Research, 1975). \n",
    "\n",
    "Let's plot a histogram of the data.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "%matplotlib inline\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "df = pd.read_csv(\"data/nidd.thresh.csv\")\n",
    "df = df[\"x\"]\n",
    "df.hist()\n",
    "plt.xlabel(\"Flow in m³/s\")\n",
    "plt.ylabel(\"Number of measures\")\n",
    "plt.title(\"Histogram of Nidd river's flows, mean=%d m³/s\" % df.mean());"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We see that most flows are under $80$ $m³/s$, a significant part is under $100$ $m³/s$, but we also see that even if the flows are in general low, it can also become $300$ $m³/s$ high.\n",
    "\n",
    "This is typically a problem where we cannot use the average value to represent anything, since most flows are under $80$ $m³/s$, and some are very high."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Warm-up questions: what is the probability to observe a flow superior to $160$ $m³/s$ ? Then $255$ $m³/s$ ?**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "n, bins, patches = plt.hist(df)\n",
    "for i, x in enumerate((bins > 160)):\n",
    "    if x and i < len(bins) - 1:\n",
    "        patches[i].set_fc(\"r\")\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The step for the last bin represent one flow, this way we even can count visually the population in all the red bins :\n",
    "\n",
    "$$P(X > 160) \\simeq nb(X_{i} > 160) / n = 11/154 = 1/14$$\n",
    "\n",
    "Using our empiric data we compute this way the probability to have a flow superior to $160$ $ m³/s$, which tells us that we have a flow of this type in average every $3.5$ years.\n",
    "\n",
    "Nothing unusual yet, right ?...\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "n, bins, patches = plt.hist(df)\n",
    "for i, x in enumerate((bins > 255)):\n",
    "    if x and i < len(bins) - 1:\n",
    "        patches[i].set_fc(\"r\")\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Histogram:\n",
    "$$P(X > 255) \\simeq nb(X_{i} > 255) / n = 3/154 $$\n",
    "\n",
    "Here again we can answer (hardly) that we therefore have a flow superior to $255$ $m³/s$ in average every $12$,$8$ years.\n",
    "\n",
    "Ok enough played, let's come to the annoying question :"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**\"You have no way to answer\" question: Now, what is the probability to observe such a flow superior to $400$ $m³/s$ ?**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "n, bins, patches = plt.hist(df)\n",
    "for i, x in enumerate((bins > 400)):\n",
    "    if x and i < len(bins) - 1:\n",
    "        patches[i].set_fc(\"r\")\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Histogram:\n",
    "$$P(X > 400) \\simeq nb(X_{i} > 400) / n = 0 $$\n",
    "\n",
    "The answer is not satisfying, because it's surely not \"impossible\" to observe a flow superior to $400$ $m³/s$.\n",
    "\n",
    "## Partial Conclusion : we cannot estimate the probability of such a flow with the histogram!\n",
    "\n",
    "And now we precisely get to what we talked about before, we want to compute the probability of an event for which we have absolutely no data, I hope this is clear now. In statistical modelling, usually, we train an algorithm with a dataset that is supposed to have the same distribution as the testing data, in other words we have datas for what we want to model. Extreme value theory comes into play here:\n",
    "\n",
    "- **\"Classic\" statistics doesn't allow to compute probabilities such that $P(X > x)$ when $x$ is beyond the maximum of our observations.**\n",
    "\n",
    "\n",
    "- **Hopefully Extreme value theory gives us tools to extrapolate beyond our datas.**\n",
    "\n",
    "A \"famous\" joke illustrates this problematic: during the night, someone is squatting at the foot of a lamppost, and a passerby asks him: \"What are you doing?\" \"I'm looking for my keys.\" \"Are you certain that you lost them around the lamppost?\", asks again the passerby. \"No, but, in fact, that's the only lighted place.\"\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Extreme value statistics is kind of like this joke, we want to make statistics where there is no light, where there is no data."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Theory: Extreme values theorem / Implementation: scipy.stats.genextreme"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The extreme values theorem can be seen as the analog of the central limit theorem.\n",
    "For a random variable $X$ and it's maximum over n observations: $X_{n,n}$. \n",
    "\n",
    "\n",
    "\n",
    "Under general conditions on the distribution of X, there is three parameters\n",
    "$a_{n}$, $b_{n}$ and $\\gamma$ such that :\n",
    "   $$\\lim_{n -> +\\infty} P(\\frac{X_{n,n} - a_{n}}{b_{n}} \\leq x) = H_{\\gamma}(x)$$\n",
    "   where:\n",
    "$$ H_{\\gamma}(x) = \\begin{cases}\n",
    "                \\exp(-\\exp(-x))            &\\text{for } \\gamma = 0\\\\\n",
    "                \\exp(-(1+\\gamma x)^{-1/\\gamma}_{+})   &\\text{for }\n",
    "                                                        \\gamma != 0\n",
    "              \\end{cases}\n",
    "$$\n",
    "   \n",
    "   with $y_{+} = max(0,y)$.\n",
    "   \n",
    "Useful vocabulary:\n",
    " - $H_{\\gamma}$ is the **generalized extreme value (GEV) distribution**.\n",
    " - $\\gamma$ is the shape parameter\n",
    " - $a_{n}$ and $b_{n}$ are scaling parameters.\n",
    " \n",
    "With different values of $\\gamma$ there is a type I, type II and type III GEV, also called the Gumbel ($\\gamma=0$), Fréchet ($\\gamma >0$) and Weibull ($\\gamma <0$) distributions.\n",
    "\n",
    "If you have a random variable $X$ and study the distribution of it's maximum over a number of samples $X_{n,n}$, this distribution must belong and must \"fall\" in the domain of attraction of one of these 3 types of GEV. \n",
    " \n",
    "(More here : https://en.wikipedia.org/wiki/Generalized_extreme_value_distribution.)\n",
    "\n",
    "**We will use the genextreme class from scipy**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "from scipy.stats import genextreme\n",
    "\n",
    "plt.figure(figsize=(10, 8))\n",
    "x = np.linspace(-4, 4, 201)\n",
    "# Please notice that in genextreme the shape parameter (gamma) equals to -gamma in our equations here\n",
    "plt.plot(\n",
    "    x,\n",
    "    genextreme.pdf(x, -0.6),\n",
    "    color=\"#00FF00\",\n",
    "    label='Fréchet (\\u03B3=0.6) : \"Heavy tails\" distributions\\\n",
    " (Cauchy, Student, Pareto..)',\n",
    ")\n",
    "plt.plot(\n",
    "    x,\n",
    "    genextreme.pdf(x, 0.0),\n",
    "    \"r\",\n",
    "    label='Gumbel (\\u03B3=0): \"Light tails\" distributions\\\n",
    " (Gaussian, Log-normal, Gamma, Exponential)',\n",
    ")\n",
    "plt.plot(\n",
    "    x,\n",
    "    genextreme.pdf(x, 0.6),\n",
    "    \"b\",\n",
    "    label='Weibull (\\u03B3=-0.6): \"Finite tails\" distributions\\\n",
    " (Uniform, Beta)',\n",
    ")\n",
    "plt.ylim(-0.01, 0.51)\n",
    "plt.legend(loc=\"upper left\")\n",
    "plt.xlabel(\"x\")\n",
    "plt.ylabel(\"Density\")\n",
    "plt.title(\"Generalized Extreme Value Distributions\")\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's use again our dataset of Nidd River, we will fit a GEV on it and estimate extreme quantiles.\n",
    "In pratice we will estimate the three parameters $\\gamma$, $a_{n}$ and $b_{n}$ such that:\n",
    "$$P(X_{n,n} \\leq x) \\simeq H_{\\gamma}(\\frac{x-a_{n}}{b_{n}})$$\n",
    "\n",
    "So first we need to turn our trimestrial data, that is our observations of $X$ into observations of X_{n,n}, lets say yearly maximums, we will create a vector of observations by taking the maximum flow for each year:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for i in range(0, int(df.shape[0] / 4)):\n",
    "    if i == 0:\n",
    "        df_max = df.iloc[4 * i : 4 * i + 4].max()\n",
    "    else:\n",
    "        df_max = np.append(df_max, df.iloc[4 * i : 4 * i + 4].max())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.hist(df_max)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "shape, loc, scale = genextreme.fit(df_max)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "-shape"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This shape parameters tells us that the GEV is a Fréchet type, with a heavy tails, which means our river's flow can sometimes be very big, we better be careful and construct strong flood protections."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can plot the fitted distribution to see that it makes sense"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.hist(df_max, normed=True)\n",
    "\n",
    "x = np.linspace(df_max.min(), df_max.max(), 1000)\n",
    "y = genextreme.pdf(x, shape, loc, scale)\n",
    "plt.plot(x, y, \"c\", linewidth=3);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**We can now calculate the probability that the river's flow exceeds 350 $m^3/s$:**\n",
    "Indeed, because the observations of $X$ that we have are independant, hence:\n",
    "$P(X_{n,n} \\leq x) = F^{n}(x)$\n",
    "and from the extreme value theorem this means $F(x) \\simeq H_{\\gamma}^{1/n}(\\frac{x-a_{n}}{b_{n}})$, taking the log and developping around $\\log(1+u)$ gives :\n",
    "$P(X\\geq x) \\simeq -\\frac{1}{n}\\log H_{\\gamma}(\\frac{x-a_{n}}{b_{n}})$\n",
    "Therefore we now have an approximation of the survival function in tail:\n",
    "\n",
    "$$ \\hat{F}(x) = P(X\\geq x) \\simeq \\begin{cases}\n",
    "                \\frac{1}{n}[1+\\gamma(\\frac{x-a_{n}}{b_{n}})]^{-1/\\gamma}        &\\text{for } \\gamma != 0\\\\\n",
    "                \\frac{1}{n}\\exp(-(\\frac{x-a_{n}}{b_{n}}))   &\\text{for }\n",
    "                                                        \\gamma = 0\n",
    "              \\end{cases}\n",
    "$$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def surv(x, n, shape, loc, scale):\n",
    "    if shape != 0:\n",
    "        surv = 1 / n * (1 - shape * (x - loc) / scale) ** (1 / shape)\n",
    "    else:\n",
    "        surv = 1 / n * np.exp(-(x - loc) / scale)\n",
    "    return surv"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "surv(400, 4, shape, loc, scale)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "1 / 0.004 / 4"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "So the probability that the trimestrial flow will be greater than $400$ $m³/s$ is  about 0.004, which means one trimester in 250, which means one time in 62.5 years! *Instead of \"never\" before*\n",
    "\n",
    "We can also answer questions like : what is the river's flow that we expect to surpass every century, because we also have the inverse of the survival function :\n",
    "\n",
    "$$ \\hat{F}^{-1}(x)\\simeq \\begin{cases}\n",
    "                a_{n} + \\frac{b_{n}}{\\gamma}[(np)^{-\\gamma} - 1]         &\\text{for } \\gamma != 0\\\\\n",
    "                a_{n} - b_{n}\\log(np)   &\\text{for }\n",
    "                                                        \\gamma = 0\n",
    "              \\end{cases}\n",
    "$$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def invsurv(p, n, shape, loc, scale):\n",
    "    if shape != 0:\n",
    "        invsurv = loc + scale / -shape * ((n * p) ** shape - 1)\n",
    "    else:\n",
    "        invsurv = loc - scale * np.log(n * p)\n",
    "    return invsurv"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "invsurv(1 / 400, 4, shape, loc, scale)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here we computed the flow that we would get every 400 trimester, that is every century : $452$ $m³/s$!\n",
    "It's too bad these guys didn't follow my tutorial before:  <center> \n",
    "<img align=\"center\" src=\"http://www.planat.ch/uploads/pics/p0032_01.jpg\" style=\"width: 600px;\"/>\n",
    "<br>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Conclusion"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**What's new :**\n",
    "- You now understand the problem with extreme quantiles in classical statistics.\n",
    "- You now know that there exist an extreme value theorem that looks like CLT that tells us there is 3 types of distributions for the max of any random variable, depending on a shape parameter $\\gamma$ : Gumbel, Fréchet, Weibull.\n",
    "- To fit such a distribution we need a dataset of maximum, and to estimate $\\gamma$, $a_{n}$ (loc) and $b_{n}$ (scale).\n",
    "- We can do that with scipy.stats.genextreme very quickly.\n",
    "- With it we can compute extreme quantiles and extreme value propabilities where we have no data to learn !!!\n",
    "\n",
    "**What's not new yet:**\n",
    "- It's sometimes hard to form a dataset of maximums, there is also a similar alternative with threshold levels instead of maximums, which is easier in general. And the distribution to fit is called a GPD (Generalized Pareto Distribution), that is in scipy.stats.pareto.\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Thanks for your attention !** **God bless you!**"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
